package org.jgs1904.apachepoidemo.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;

import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class InsertImageToCellExample {

    public static void main(String[] args) {
        String imagePath = "image.jpg";  // 图片的路径
        String outputFilePath = "output.xlsx";  // 输出文件路径

        try {
            // 创建工作簿和工作表
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("Sheet1");

            // 读取图片文件
            File imageFile = new File(imagePath);
            BufferedImage bufferedImage = ImageIO.read(imageFile);

            // 插入图片到单元格
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
            anchor.setCol1(0);
            anchor.setRow1(0);
            anchor.setCol2(1);
            anchor.setRow2(1);

            int pictureIndex = workbook.addPicture(IOUtils.toByteArray(new FileInputStream(imageFile)), Workbook.PICTURE_TYPE_JPEG);
            Picture picture = drawing.createPicture(anchor, pictureIndex);

            // 调整图片尺寸以适应单元格
            int cellWidth = sheet.getColumnWidth(0);
            short cellHeight = sheet.getDefaultRowHeight();
            int imageWidth = bufferedImage.getWidth();
            int imageHeight = bufferedImage.getHeight();

            double scaleX = (double) cellWidth / imageWidth;
            double scaleY = (double) cellHeight / imageHeight;
            double scale = Math.min(scaleX, scaleY);

            int targetWidth = (int) (imageWidth * scale);
            int targetHeight = (int) (imageHeight * scale);

            picture.resize(targetWidth, targetHeight);

            // 保存工作簿到文件
            FileOutputStream fos = new FileOutputStream(outputFilePath);
            workbook.write(fos);
            fos.close();

            System.out.println("图片已成功插入到单元格中！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}